package com.jc.service.zflservice;

import com.alibaba.fastjson.JSONObject;
import com.jc.cds.model.CustomXorder;
import com.jc.common.util.DateTimeUtil;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.OrderProducts;
import com.jc.ds.model.Xorder;
import com.jc.ds.model.XorderMarge;
import com.jc.ds.model.XorderProcess;
import com.jc.framework.enums.*;
import com.jc.service.jctask.JcTaskService;
import com.jc.service.model.zfl.ZflOrderAddress;
import com.jc.service.model.zfl.ZflOrderItems;
import com.jc.service.model.zfl.ZflPushOrder;
import com.jc.service.order.XorderService;
import com.jc.service.orderproduct.OrderProductsService;
import com.jc.service.systemloglist.SystemLogListService;
import com.jc.service.xordermarge.XorderMargeService;
import com.jc.service.xorderprocess.XorderProcessService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@SuppressWarnings("all")
@Service
public class ZflOrderServiceImpl implements ZflOrderService {

    @Autowired
    private OrderProductsService orderProductsService;
    @Autowired
    private SystemLogListService systemLogListService;
    @Autowired
    private XorderMargeService xorderMargeService;
    @Autowired
    private XorderProcessService xorderProcessService;
    @Autowired
    private XorderService xorderService;
    @Autowired
    private JcTaskService jcTaskService;

    /**
     * 订单推送给供应商
     * */
    @Transactional
    @Override
    public void orderPush(CustomXorder xorder) {
        //封装成推送对象
        ZflPushOrder zflPushOrder = packageZflOrder(xorder);
        Map<String,Object> param = new HashMap<>();
        param.put("order",zflPushOrder);
        String resultStr = null;
        try {
            resultStr = ZflCommonUtil.ZFLHttpUtil(ZFLApi.ORDER_PUSH.getName(), ZFLApi.ORDER_PUSH.getDesc(), param);
            if (!"0".equals(JSONObject.parseObject(resultStr,Map.class).get("resultCode"))){
                throw new BaseServiceException("推送订单失败,原因:"+JSONObject.parseObject(resultStr,Map.class).get("resultDesc"));
            }
            XorderProcess xorderProcess = new XorderProcess();
            xorderProcess.setChannelOrderId(xorder.getChannelOrderId());
            xorderProcess.setDetailDesc("成功推送订单到最福利供应商");
            xorderProcess.setOptionUserName("系统定时");
            xorderProcess.setOrderId(xorder.getId());
            xorderProcess.setProcessCreate(new Date());
            xorderProcessService.add(xorderProcess,false);
            systemLogListService.addSystemLog(JSONObject.toJSONString(param), Conclusion.OK, null, LogType.ZFL_PUSH_ORDER, resultStr);

            //推送至供应商成功 , 创建定时任务 .
            jcTaskService.addTask(TaskType.push_express,String.valueOf(xorder.getId()),JSONObject.toJSONString(param),Booleans.FALSE,null);
        } catch (Exception e) {
            XorderProcess xorderProcess = new XorderProcess();
            xorderProcess.setChannelOrderId(xorder.getChannelOrderId());
            xorderProcess.setDetailDesc("推送订单到最福利供应商失败");
            xorderProcess.setOptionUserName("系统定时");
            xorderProcess.setOrderId(xorder.getId());
            xorderProcess.setProcessCreate(new Date());
            xorderProcessService.add(xorderProcess,false);
            systemLogListService.addSystemLog(JSONObject.toJSONString(param), Conclusion.FAIL, null, LogType.ZFL_PUSH_ORDER, resultStr);

            Xorder xorderUpdate = new Xorder();
            xorderUpdate.setId(xorder.getId());
            xorderUpdate.setSupplierOrderNo(null);
            xorderUpdate.setOrderStatus(OrderStatus.push_final.getName());
            xorderService.modify(xorderUpdate,false);

            //推送至供应商失败 , 创建定时任务 .
            jcTaskService.addTask(TaskType.push_express,String.valueOf(xorder.getId()),JSONObject.toJSONString(param),Booleans.FALSE,null);
            e.printStackTrace();
        }
        //转成json 把返回的订单号填充到xorder
        Map<String,Object> bizContent = JSONObject.parseObject(JSONObject.parseObject(resultStr, Map.class).get("bizContent").toString(), Map.class);
        List<Long> orderIds = JSONObject.parseObject(bizContent.get("orderIds").toString(),List.class);
        if (orderIds == null){
            throw new BaseServiceException("供应商未返回订单编号,订单id为:"+xorder.getId());
        }else if(orderIds.size() > 1){
            throw new BaseServiceException("供应商返回多条订单编号,订单id为"+xorder.getId()+",返回的订单编号为,"+ StringUtils.join(orderIds,","));
        }else{
            //正确 , 确认订单
            Map<String,Object> paramOrder = new HashMap<>();
            paramOrder.put("orderIds",new ArrayList<Long>(){{
                add(orderIds.get(0));
            }});
            try {
                String result = ZflCommonUtil.ZFLHttpUtil(ZFLApi.ORDER_CONFIRM.getName(), ZFLApi.ORDER_CONFIRM.getDesc(), paramOrder);
                if (!"0".equals(JSONObject.parseObject(result,Map.class).get("resultCode"))){
                    throw new BaseServiceException("确认订单失败,原因:"+JSONObject.parseObject(result,Map.class).get("resultDesc"));
                }
                XorderProcess xorderProcess = new XorderProcess();
                xorderProcess.setChannelOrderId(xorder.getChannelOrderId());
                xorderProcess.setDetailDesc("最福利供应商确认订单成功");
                xorderProcess.setOptionUserName("系统定时");
                xorderProcess.setOrderId(xorder.getId());
                xorderProcess.setProcessCreate(new Date());
                xorderProcessService.add(xorderProcess,false);
                systemLogListService.addSystemLog(JSONObject.toJSONString(paramOrder), Conclusion.OK, null, LogType.ZFL_PUSH_ORDER, resultStr);
            } catch (Exception e) {
                XorderProcess xorderProcess = new XorderProcess();
                xorderProcess.setChannelOrderId(xorder.getChannelOrderId());
                xorderProcess.setDetailDesc("最福利供应商确认订单失败");
                xorderProcess.setOptionUserName("系统定时");
                xorderProcess.setOrderId(xorder.getId());
                xorderProcess.setProcessCreate(new Date());
                xorderProcessService.add(xorderProcess,false);
                systemLogListService.addSystemLog(JSONObject.toJSONString(paramOrder), Conclusion.FAIL, null, LogType.ZFL_PUSH_ORDER, resultStr);
                Xorder xorderUpdate = new Xorder();
                xorderUpdate.setId(xorder.getId());
                xorderUpdate.setSupplierOrderNo(orderIds.get(0).toString());
                xorderUpdate.setOrderStatus(OrderStatus.push_final.getName());
                xorderService.modify(xorderUpdate,false);
                e.printStackTrace();
            }
            //更新第三方订单编号
            Xorder xorderUpdate = new Xorder();
            xorderUpdate.setId(xorder.getId());
            xorderUpdate.setSupplierOrderNo(orderIds.get(0).toString());
            xorderUpdate.setOrderStatus(OrderStatus.push_ok.getName());
            xorderService.modify(xorderUpdate,false);
        }
    }

    /**
     * 封装发送到供应商的实体类
     * */
    public ZflPushOrder packageZflOrder(CustomXorder order){
        ZflPushOrder zflPushOrder = new ZflPushOrder();
        //收货人地址
        ZflOrderAddress zflOrderAddress = new ZflOrderAddress();
        zflOrderAddress.setProvinceName(order.getConsigneeProvinceName());//省
        zflOrderAddress.setCityName(order.getConsigneeCityName());//shi
        zflOrderAddress.setDistrictName(order.getConsigneeRegionName());//qu
        //zflOrderAddress.setProvinceName(order.getConsigneeProvinceName());//TODO 城镇不存在不传
        zflOrderAddress.setStreet(order.getConsigneeAddress());//详细地址
        zflOrderAddress.setName(order.getConsigneeName());//收货人
        if (StringUtils.isNotBlank(order.getConsigneeMobile())){
            zflOrderAddress.setPhone(order.getConsigneeMobile());
        }else{
            zflOrderAddress.setPhone(order.getConsigneePhone());
        }
        zflPushOrder.setShipAddress(zflOrderAddress);

        zflPushOrder.setBuyerNotes(order.getBuyerMemo());
        String channelOrderId = order.getChannelOrderId();
        //查询是否存在合并后的订单号
        XorderMarge xorderMarge = xorderMargeService.getXorderMarge(order.getId());
        if (xorderMarge != null){
            channelOrderId = xorderMarge.getChannelOrderId();
        }
        zflPushOrder.setOutOrderId(channelOrderId);
        //封装sku
        //根据id和是否捆绑商品
        List<OrderProducts> skus = orderProductsService.queryProductByOrderId(order.getId());
        List<ZflOrderItems> items = new ArrayList<>();
        skus.forEach(sku->{
            ZflOrderItems zflOrderItems = new ZflOrderItems();
            zflOrderItems.setSkuId(Long.valueOf(sku.getSupplierProductId()));
            zflOrderItems.setQuantity(sku.getProductNums());
            items.add(zflOrderItems);
        });
        zflPushOrder.setItems(items);
        return zflPushOrder;
    }
}
